<?php
##############################################
#
#   用户
# @ Time : 2017-3-1 - 下午11:55:14
# @ Author : JiangYongWei <1085562810@qq.com>
# @ Encoding : UTF-8 language : PHP
#
##############################################

namespace Home\Controller;
use Think\Controller;

class ApplyController extends BaseController{

	/**
	 * 专家预约中心页
	 */
	public function apply(){
            $sourch = I('name');
            $type = I('get.type');
            //判断是否已经是专家
            $is_apply = M('users')->where('id='. session('user_id'))->field('expert_type')->find();
            if(!$is_apply['expert_type']){
                $this->assign('apply_count',1);
            }
            //轮播图
            self::benner();
            //全部
	    self::allApply();
	    //军事专家
	    self::MilitaryApply();
	    //国防专家
	    self::DefenceApply();
	    //医学专家
	    self::MedicineApply();
            $this->assign('name',$sourch);
            $this->assign('type',$type);
            $this->display();
        
	}
	 
        /**
	 * 全部
	 */
	public function allApply(){
            $sourch = I('name');
            $map['user_name'] = array('like','%'.$sourch.'%');
            $count = M('apply')->where($map)->where("status = 1")->count();// 查询满足要求的总记录数
	    $Page = new \Think\Page($count, 5);
	    $show = $Page->show();
            $all_apply = M('apply')->where($map)->where("status = 1")->order('id desc')->limit($Page->firstRow.','.$Page->listRows)->select();
            foreach($all_apply as $k=>$v){
                //关注
                $all_apply[$k]['collection'] = M('make_collection')->where('make_id='.$all_apply[$k]['id'].' and user_id='.  session('user_id'))->count();
            }
	    $this->assign('all_apply',$all_apply);
	    if(count($all_apply) > 0){
	        $this->assign('all_show', 1);
	    }
	    if ($_GET['is_ajax']) {
	        $this->display('ajax_apply_all_list');
	        exit;
	    }
	}
        
         /**
	 * 军事专家
	 */
	public function MilitaryApply(){
            $sourch = I('name');
            $map['user_name'] = array('like','%'.$sourch.'%');
            $count = M('apply')->where($map)->where("status = 1 and type=1")->count();// 查询满足要求的总记录数
            $Page = new \Think\Page($count, 5);
	    $show = $Page->show();
	    $military_apply = M('apply')->where($map)->where("status = 1 and type=1")->order('id desc')->limit($Page->firstRow.','.$Page->listRows)->select();
            foreach($military_apply as $k=>$v){
                //关注
                $military_apply[$k]['collection'] = M('make_collection')->where('make_id='.$military_apply[$k]['id'].' and user_id='.  session('user_id'))->count();
            }
	    $this->assign('military_apply',$military_apply);
	    if(count($military_apply) > 0){
	        $this->assign('military_show', 1);
	    }
	    if ($_GET['is_ajax']) {
	        $this->display('ajax_military_list');
	        exit;
	    }
	}
        
        /**
	 * 国防专家
	 */
	public function DefenceApply(){
            $sourch = I('name');
            $map['user_name'] = array('like','%'.$sourch.'%');
            $count = M('apply')->where($map)->where("status = 1 and type=2")->count();// 查询满足要求的总记录数
	    $Page = new \Think\Page($count, 5);
	    $show = $Page->show();
	    $defence_apply = M('apply')->where($map)->where("status = 1 and type=2")->order('id desc')->limit($Page->firstRow.','.$Page->listRows)->select();
	    foreach($defence_apply as $k=>$v){
                //关注
                $defence_apply[$k]['collection'] = M('make_collection')->where('make_id='.$defence_apply[$k]['id'].' and user_id='.  session('user_id'))->count();
            }
            $this->assign('defence_apply',$defence_apply);
	    if(count($defence_apply) > 0){
	        $this->assign('defence_show', 1);
	    }
	    if ($_GET['is_ajax']) {
	        $this->display('ajax_defence_list');
	        exit;
	    }
	}
        
        /**
	 * 医学专家
	 */
	public function MedicineApply(){
            $sourch = I('name');
            $map['user_name'] = array('like','%'.$sourch.'%');
            $count = M('apply')->where($map)->where("status = 1 and type=3")->count();// 查询满足要求的总记录数
	    $Page = new \Think\Page($count, 5);
	    $show = $Page->show();
	    $medicine_apply = M('apply')->where($map)->where("status = 1 and type=3")->order('id desc')->limit($Page->firstRow.','.$Page->listRows)->select();
	    foreach($medicine_apply as $k=>$v){
                //关注
                $medicine_apply[$k]['collection'] = M('make_collection')->where('make_id='.$medicine_apply[$k]['id'].' and user_id='.  session('user_id'))->count();
            }
            $this->assign('medicine_apply',$medicine_apply);
	    if(count($medicine_apply) > 0){
	        $this->assign('medicine_show', 1);
	    }
	    if ($_GET['is_ajax']) {
	        $this->display('ajax_medicine_list');
	        exit;
	    }
	}
        
        /**
	 * 专家中心分页
	 */
        public function ajax_apply() {

        $user_id = session('user_id');
        
        if(IS_AJAX){
            $data = I('post.');
            if($data['id'] == 0){
                $map['type'] = array('neq', $data['id']);
            }
            if ($data['id'] && $data['id']!=0) {
                $map['type'] = array('eq', $data['id']);
            }
            if ($data['name']) {
                $map['name'] = array('like', '%' . $data['name'] . '%');
            }
            $make = M('make')->where($map)->where('trial_status=2')->order('is_top desc,add_time desc')->select();
            if(!$make){
                echo '<p style="text-align: center;">没有数据了...</p>';
            }
            foreach ($make as $k => $v) {
                //判断是否已经关注该活动
                $make[$k]['collection'] = M('make_collection')->where('make_id=' . $make[$k]['id'] . ' and user_id=' . $user_id)->count();
            }
            $this->assign('make', $make);
        }
        $this->display('ajax_apply');
    }

    //关注
        public function ajaxGuanzhu(){
            $user_id = session('user_id');
            
                $id = I('id');
                if($id && $user_id){
                    $count = M('make_collection')->where('make_id='.$id.' and user_id='.$user_id)->count();
                    if($count){
                        $this->ajaxReturn(array('status'=>2));
                    }
                    $users_status = M('users')->where('id='.$user_id.' and user_type<3')->count();
                    if($users_status){
                         $this->ajaxReturn(array('status'=>3));
                    }
                        $data = array(
                            'user_id'=>$user_id,
                            'make_id'=>$id,
                            'create_time'=>time()
                        );
                        $collection = M('make_collection')->add($data);
                        if($collection){
                            $this->ajaxReturn(array('status'=>1));
                        }else{
                            $this->ajaxReturn(array('status'=>2));
                        }
                }
            
        }


//预约
        public function ajaxYuyue(){
            $user_id = session('user_id');
            
                $id = I('id');
                if($id && $user_id){
                    $count = M('make_users')->where('make_id='.$id.' and user_id='.$user_id)->count();
                    if($count){
                        $this->ajaxReturn(array('status'=>2));
                    }
                    $users_status = M('users')->where('id='.$user_id.' and user_type!=1')->count();
                    if($users_status){
                         $this->ajaxReturn(array('status'=>3));
                    }
                        $data = array(
                            'user_id'=>$user_id,
                            'make_id'=>$id,
                            'create_time'=>time()
                        );
                        $collection = M('make_users')->add($data);
                        if($collection){
                            $this->ajaxReturn(array('status'=>1));
                        }else{
                            $this->ajaxReturn(array('status'=>2));
                        }
                }
            
        }
        
        
                /**
	 * 专家申请
	 */
	public function expert_join(){
            $user_id = session('user_id');
            $userType = M('users')->where('id='.$user_id)->find();
            if($userType['user_type'] < 2){
                self::promptPage('对不起，您还不是正式会员，请绑定手机成为会员！', U("Index/applyUser"), false, '立马绑定');
	        }
            if(IS_POST){
                $data = I('post.');
                $data['user_id'] = $user_id;
                $data['add_time'] = time();
                $expert_type['expert_type'] = $data['type'];
                    //证明材料上传
                    if($_FILES['img']['name']){
                        $photo_img = \Home\Model\ApplyModel::upload(900, 255);
                        $data['img'] = $photo_img['img'];   //serialize($photo_img)
                        if($data['old_img']){
                            @unlink($_SERVER['DOCUMENT_ROOT'].substr(__APP__, 1).$data['old_img']);
                        }
                    }
                    //一寸证件照上传
                    if($_FILES['headimgurl']['name']){
                        $photo_img = \Home\Model\ApplyModel::upload(900, 255);
                        $data['headimgurl'] = $photo_img['headimgurl'];   //serialize($photo_img)
                        if($data['old_headimgurl']){
                            @unlink($_SERVER['DOCUMENT_ROOT'].substr(__APP__, 1).$data['old_headimgurl']);
                        }
                    }
                    //多图上传
                    if($_FILES['more_img']['name'][0]){
                        if(count($_FILES['more_img']['name'])>10){
                            self::promptPage('最多只能上传10张照片！', U("Apply/expert_join"), false, '返回');
                        }
                            $photo_img = \Home\Model\ApplyModel::uploadImg();
                            $data['more_img'] = serialize($photo_img);   //serialize($photo_img)
                            if($data['old_more_img']){
                                @unlink($_SERVER['DOCUMENT_ROOT'].substr(__APP__, 1).$data['old_more_img']);
                            }
                    }
                    $count = M('apply')->where('user_id='.$user_id)->count();
                    if($count){             //修改
                        $data['status'] = 2;
                        $save = M('apply')->where('user_id='.$user_id)->save($data);
                        if($save){
                            M('users')->where('id='.$user_id)->save($expert_type);
                            self::promptPage('修改成功，我们正在快马加鞭给你审核！', U("Users/index"), false, '确定');
                        }  else {
                            exit("修改失败");
                        }
                    }  else {               //添加
                        $data['headimgurl'] = $userType['headimgurl'];
                        $value = M('apply')->add($data);
                        if($value){
                            M('users')->where('id='.$user_id)->save($expert_type);
                            self::promptPage('申请成功，我们正在快马加鞭给你审核！', U("Users/index"), false, '确定');
                        }  else {
                            exit('申情失败');
                        }
                    }
                
            }else{
                $apply = M('apply')->where('user_id='.$user_id)->find();
                $photoes = unserialize($apply['more_img']);
                $apply['more_img_list'] = $photoes['S'];
                $this->assign('apply',$apply);
                $this->display();
            }
	    
	}
        
        /**
	 * 专家详情
	 */
        public function expert_page(){
            $id = I('id');
            //浏览量
            $visit_number = M('apply')->where('id='.$id)->setInc('visit_number');
            //专家详情
            $apply_one = M('apply')->where('id='.$id)->find();
            $img = unserialize($apply_one['more_img']);
            $apply_one['more_img_list'] = $img['M'];
            //可预约专家的时间
            $make_one = M('make')->where('user_id='.  $apply_one['user_id'])->order('add_time desc')->find();
            $monday = strtotime(date("Y-m-d H:i:s",mktime(0, 0 , 0,date("m"),date("d")-date("w")+1,date("Y"))));
            $sunday = strtotime(date("Y-m-d H:i:s",mktime(23,59,59,date("m"),date("d")-date("w")+7,date("Y"))));
            if ($monday <= $make_one['add_time'] && $make_one['add_time'] <= $sunday) {
            $make_one['select_time'] = explode(',', $make_one['select_time']);
            $selectTime = $make_one['select_time'];
            $make_users = M('make_users')->where('make_id='.$make_one['id'].' and status!=3')->field('select_time')->select();
            foreach ($make_users as $key => $value) {
                foreach ($selectTime as $k => $v) {
                    if ($v == $value['select_time']) {
                        unset($selectTime[$k]);
                    }
                }
            }
            if (!$selectTime) {
                $this->assign('yuyue_show', 1);
            }
            foreach ($selectTime as $kk => $vv) {
                $weekarray = array("'星期日'", "'星期一'", "'星期二'", "'星期三'", "'星期四'", "'星期五'", "'星期六'");
                $select_time[$kk] = $weekarray[$vv];
                $select = implode(',', $select_time);
            }
            $make_one['select_time'] = $select;
            $this->assign('make_one', $make_one);
        } else {
            $this->assign('yuyue_show', 1);
        }
        //相关活动
            self::ajax_expert_page();
            //相关评论
            $comment = M('comment')
                    ->alias('c')
                    ->field('c.*,u.headimgurl')
                    ->join('__USERS__ AS u ON u.id=c.user_id')
                    ->where('id_value='.$id.' and comment_type=2')
                    ->order('c.add_time desc')
                    ->limit(3)
                    ->select();
            if(count($comment)>0){
                $this->assign('comment_show',1);
            }
            //判断是否已经是专家
            $is_apply = M('users')->where('id='. session('user_id'))->field('expert_type')->find();
            if(!$is_apply['expert_type']){
                $this->assign('apply_count',1);
            }
            $comment_count = M('comment')->where('id_value='.$id.' and comment_type=2')->count();
            $this->assign('apply_one',$apply_one);
            $this->assign('comment',$comment);
            $this->assign('id',$id);
            $this->assign('count',$comment_count);
	    $this->display();
	}
	 /**
	 * 专家详情->相关活动
	 */
        public function ajax_expert_page(){
            $user_id = session('user_id');
            $count = M('activity')->where('user_id='.$user_id)->count();
            $Page = new \Think\Page($count,2);
            $show = $Page->show();
            $activity = M('activity')->where('user_id='.$user_id)->limit($Page->firstRow.','.$Page->listRows)->select();
            $this->assign('activity',$activity);
            if(count($activity)>0){
                $this->assign('activity_show',1);
            }
             if ($_GET['is_ajax']) {
	        $this->display('ajax_expert_page');
	        exit;
	    }
        }
        
        //预约
        public function expert_page_yuyue(){
            $user_id = session('user_id');
            if(IS_POST){
                $data = I('post.');
                $make_self = M('apply')->where('id='.$data['id'].' and user_id='.$user_id)->count();
                if($make_self>0){
                    $this->ajaxReturn(array('status'=>2,'message'=>'你不能预约自己'));
                }
                $pattern = '/^0?(13|14|15|17|18)[0-9]{9}$/';
                if(!$data['username']){
                    $this->ajaxReturn(array('status'=>2,'message'=>'姓名不能为空'));
                }
                if(!$data['phone']){
                    $this->ajaxReturn(array('status'=>2,'message'=>'手机号码不能为空'));
                }
                if(!preg_match($pattern,$data['phone'])){
                    $this->ajaxReturn(array('status'=>2,'message'=>'手机号码格式不正确'));
                }
                if(!$data['address']){
                    $this->ajaxReturn(array('status'=>2,'message'=>'地址不能为空'));
                }
                if(!$data['select_time']){
                    $this->ajaxReturn(array('status'=>2,'message'=>'请选择预约时间'));
                }
                
                if($data['select_time']=='星期一'){
                    $data['select_time'] = 1;
                }
                if($data['select_time']=='星期二'){
                    $data['select_time'] = 2;
                }
                if($data['select_time']=='星期三'){
                    $data['select_time'] = 3;
                }
                if($data['select_time']=='星期四'){
                    $data['select_time'] = 4;
                }
                if($data['select_time']=='星期五'){
                    $data['select_time'] = 5;
                }
                if($data['select_time']=='星期六'){
                    $data['select_time'] = 6;
                }
                if($data['select_time']=='星期日'){
                    $data['select_time'] = 0;
                }
                $make_one = M('make_users')->where('id='.$data['id'].' and user_id='.$user_id)->where('select_time='.$data['select_time'].' and status!=3')->count();
                if($make_one){
                    $this->ajaxReturn(array('status'=>2,'message'=>'你已经预约过了，请换一个时间吧'));
                }
                $arr = array(
                    'user_id'=>$user_id,
                    'username'=>$data['username'],
                    'make_id'=>$data['id'],
                    'address'=>$data['address'],
                    'phone'=>$data['phone'],
                    'pay'=>$data['pay'],
                    'select_time'=>$data['select_time'],
                    'create_time'=>time()
                );
                $makeUser = M('make_users')->add($arr);
                if($makeUser){
                    $this->ajaxReturn(array('status'=>1,'message'=>'预约成功，近期专家会与你联系'));
                }else{
                    $this->ajaxReturn(array('status'=>2,'message'=>'预约失败'));
                }
            }
            $this->display();
        }

        
        //评论列表和发表评论
        public function discuss_list(){
            $id = I('get.id');
            $ip = getIP();
            $user_id = session('user_id');
            if(IS_AJAX){
                $data = I('post.');
                $data_id = $data['id'];
                $map['id_value'] = $data_id;
                $comment = M('comment')->where('user_id='.$user_id.' and comment_type=2')->where($map)->count();
                if($comment){
                    $this->ajaxReturn(array('status'=>2,'message'=>'你已经评论过了'));
                }
                $count_user = M('make_users')->where('make_id='.$data['id'].' and user_id='.$user_id.' and status=2')->count();
                if(!$count_user){
                    $this->ajaxReturn(array('status'=>2,'message'=>'你还没参与预约或者预约还没结束'));
                }
                $users = M('users')->where('id='.$user_id)->field('email,nickname')->find();
                $arr = array(
                    'comment_type'=>2,
                    'id_value'=>$data['id'],
                    'email'=>$users['email'],
                    'user_name'=>$users['nickname'],
                    'content'=>$data['content'],
                    'ip_address'=>$ip,
                    'add_time'=>time(),
                    'user_id'=>$user_id,
                );
                $rel = M('comment')->add($arr);
                if($rel){
                    $this->ajaxReturn(array('status'=>1,'message'=>'评论成功'));
                }else{
                    $this->ajaxReturn(array('status'=>2,'message'=>'评论失败'));
                }
            } else {
            $comment = M('comment')
                    ->alias('c')
                    ->field('c.*,u.headimgurl')
                    ->join('__USERS__ AS u ON u.id=c.user_id')
                    ->where('c.id_value=' . $id . ' and c.comment_type=2 and status=1')
                    ->order('c.add_time desc')
                    ->select();
            $this->assign('id', $id);
            $this->assign('comment', $comment);
        }
        $this->display();
        }

        //我的预约列表
        public function expert_discuss(){
            $user_id = session('user_id');
            $count = M('make_users')->where('user_id='.$user_id)->count();
            $Page = new \Think\Page($count,5);
            $show = $Page->show();
            $make_users = M('make_users')
                    ->alias('u')
                    ->field('u.id,u.make_id,u.select_time,u.address,u.status,m.name,m.mobile,m.head_img,a.id as apply_id')
                    ->join('__MAKE__ AS m ON m.id=u.make_id')
                    ->join('__APPLY__ AS a ON a.user_id=m.user_id')
                    ->where('u.user_id='.$user_id)
                    ->order('u.create_time desc')
                    ->limit($Page->firstRow.','.$Page->listRows)
                    ->select();
            if(count($make_users)>0){
                $this->assign('make_users_show',1);
            }
            $this->assign('make_users',$make_users);
            if ($_GET['is_ajax']) {
	        $this->display('ajax_expert_discuss');
	        exit;
	    }
            $this->display();
        }

        /**
	  * 提示页面
	  * @param string $message 提示内容
	  * @param string $jump_url 跳转链接
	  * @param boolean $back 返回
	  * @param string $text 按钮文字
	  * @date 2017年9月12日 - 下午2:53:47
	  * @author JiangYongWei
	 */
	public function promptPage($message, $jump_url='', $back=false, $text){
	    $this->assign('title', '提示');
	    $this->assign('message', $message);
	    $this->assign('jump_url', $jump_url);
	    $this->assign('text', $text);
	    if($back){
	        $this->assign('back', 1);
	    }
	    $this->display('Public/publish_tishi');
	    exit;
	}

         //结束预约
        public function success_yuyue(){
            $id = I('post.id');
            $map['status'] = 2;
            $make_users_status = M('make_users')->where('id='.$id)->save($map);
            if($make_users_status){
                $this->ajaxReturn(array('status'=>1,'message'=>'操作成功'));
            }else{
                $this->ajaxReturn(array('status'=>2,'message'=>'操作失败'));
            }
        }
        
          //取消预约
        public function release_yuyue(){
            $id = I('post.id');
            $map['status'] = 3;
            $make_users_status = M('make_users')->where('id='.$id)->save($map);
            if($make_users_status){
                $this->ajaxReturn(array('status'=>1,'message'=>'操作成功'));
            }else{
                $this->ajaxReturn(array('status'=>2,'message'=>'操作失败'));
            }
        }
        
        //查看预约我的客户
        public function view_discuss(){
            $make_id = I('id');
            $make_users = M('make_users')
                    ->alias('m')
                    ->field('m.*,u.headimgurl')
                    ->join('__USERS__ as u on u.id = m.user_id')
                    ->where('m.make_id='.$make_id)
                    ->order('m.create_time desc')
                    ->select();
            if(count($make_users)>0){
                $this->assign('make_users_show',1);
            }
            $this->assign('make_users',$make_users);
            if($_GET['is_ajax']){
                $this->display('ajax_view_discuss');
            }
            $this->display();
        }
}